const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const db = require('../config/database');

router.use(authenticateToken);

// ========================================
// 🏆 成就系统
// ========================================

// 获取用户成就列表
router.get('/achievements', async (req, res) => {
    try {
        const userId = req.user.user_id;
        
        // 获取所有成就定义
        const [allAchievements] = await db.query(`
            SELECT * FROM achievements ORDER BY achievement_type, requirement_value
        `);
        
        // 获取用户已获得的成就
        const [userAchievements] = await db.query(`
            SELECT achievement_id, achieved_at 
            FROM user_achievements 
            WHERE user_id = ?
        `, [userId]);
        
        // 合并数据
        const achievedIds = new Set(userAchievements.map(a => a.achievement_id));
        const achievements = allAchievements.map(ach => ({
            ...ach,
            achieved: achievedIds.has(ach.achievement_id),
            achieved_at: userAchievements.find(ua => ua.achievement_id === ach.achievement_id)?.achieved_at || null
        }));
        
        res.json({ code: 200, data: achievements });
    } catch (error) {
        console.error('获取成就列表失败:', error);
        res.status(500).json({ code: 500, message: '获取失败', error: error.message });
    }
});

// 检查并解锁成就
router.post('/achievements/check', async (req, res) => {
    try {
        const userId = req.user.user_id;
        const newAchievements = [];
        
        // 获取用户统计数据
        const [userStats] = await db.query(`
            SELECT 
                ul.total_records,
                ul.streak_days,
                COUNT(DISTINCT r.category) as category_count
            FROM user_levels ul
            LEFT JOIN records r ON r.user_id = ul.user_id AND r.type = 'expense'
            WHERE ul.user_id = ?
            GROUP BY ul.user_id
        `, [userId]);
        
        if (userStats.length === 0) return res.json({ code: 200, data: { newAchievements: [] } });
        
        const stats = userStats[0];
        
        // 检查基础记账成就
        const recordMilestones = [
            { key: 'first_record', value: 1 },
            { key: 'record_10', value: 10 },
            { key: 'record_50', value: 50 },
            { key: 'record_100', value: 100 },
            { key: 'record_365', value: 365 }
        ];
        
        for (const milestone of recordMilestones) {
            if (stats.total_records >= milestone.value) {
                const unlocked = await unlockAchievement(userId, milestone.key);
                if (unlocked) newAchievements.push(unlocked);
            }
        }
        
        // 检查连续记账成就
        const streakMilestones = [
            { key: 'streak_7', value: 7 },
            { key: 'streak_30', value: 30 },
            { key: 'streak_100', value: 100 }
        ];
        
        for (const milestone of streakMilestones) {
            if (stats.streak_days >= milestone.value) {
                const unlocked = await unlockAchievement(userId, milestone.key);
                if (unlocked) newAchievements.push(unlocked);
            }
        }
        
        // 检查分类成就
        if (stats.category_count >= 5) {
            const unlocked = await unlockAchievement(userId, 'category_5');
            if (unlocked) newAchievements.push(unlocked);
        }
        if (stats.category_count >= 9) {
            const unlocked = await unlockAchievement(userId, 'category_all');
            if (unlocked) newAchievements.push(unlocked);
        }
        
        res.json({ code: 200, data: { newAchievements } });
    } catch (error) {
        console.error('检查成就失败:', error);
        res.status(500).json({ code: 500, message: '检查失败', error: error.message });
    }
});

// 解锁成就的辅助函数
async function unlockAchievement(userId, achievementKey) {
    try {
        // 获取成就信息
        const [achievements] = await db.query(
            'SELECT * FROM achievements WHERE achievement_key = ?',
            [achievementKey]
        );
        
        if (achievements.length === 0) return null;
        const achievement = achievements[0];
        
        // 检查是否已解锁
        const [existing] = await db.query(
            'SELECT * FROM user_achievements WHERE user_id = ? AND achievement_id = ?',
            [userId, achievement.achievement_id]
        );
        
        if (existing.length > 0) return null; // 已解锁
        
        // 解锁成就
        await db.query(
            'INSERT INTO user_achievements (user_id, achievement_id) VALUES (?, ?)',
            [userId, achievement.achievement_id]
        );
        
        // 增加用户积分
        await db.query(
            'UPDATE user_levels SET total_points = total_points + ? WHERE user_id = ?',
            [achievement.points, userId]
        );
        
        return {
            name: achievement.achievement_name,
            icon: achievement.achievement_icon,
            points: achievement.points
        };
    } catch (error) {
        console.error('解锁成就失败:', error);
        return null;
    }
}

// ========================================
// ⭐ 等级系统
// ========================================

// 获取用户等级信息
router.get('/level', async (req, res) => {
    try {
        const userId = req.user.user_id;
        
        // 获取用户等级数据
        const [userLevels] = await db.query(`
            SELECT * FROM user_levels WHERE user_id = ?
        `, [userId]);
        
        if (userLevels.length === 0) {
            // 初始化用户等级
            await db.query(
                'INSERT INTO user_levels (user_id) VALUES (?)',
                [userId]
            );
            return res.json({
                code: 200,
                data: {
                    level: 1,
                    level_name: '新手',
                    level_icon: '🌱',
                    exp: 0,
                    next_level_exp: 100,
                    total_points: 0,
                    total_records: 0,
                    streak_days: 0,
                    progress: 0
                }
            });
        }
        
        const userLevel = userLevels[0];
        
        // 获取当前等级配置
        const [currentConfig] = await db.query(
            'SELECT * FROM level_config WHERE level = ?',
            [userLevel.level]
        );
        
        // 获取下一等级配置
        const [nextConfig] = await db.query(
            'SELECT * FROM level_config WHERE level = ?',
            [userLevel.level + 1]
        );
        
        const current = currentConfig[0] || { level_name: '新手', level_icon: '🌱' };
        const next = nextConfig[0];
        
        const nextLevelExp = next ? next.required_exp : 999999;
        const progress = (userLevel.exp / nextLevelExp * 100).toFixed(1);
        
        res.json({
            code: 200,
            data: {
                level: userLevel.level,
                level_name: current.level_name,
                level_icon: current.level_icon,
                exp: userLevel.exp,
                next_level_exp: nextLevelExp,
                total_points: userLevel.total_points,
                total_records: userLevel.total_records,
                streak_days: userLevel.streak_days,
                progress: parseFloat(progress),
                unlocks: current.unlocks ? JSON.parse(current.unlocks) : null
            }
        });
    } catch (error) {
        console.error('获取等级信息失败:', error);
        res.status(500).json({ code: 500, message: '获取失败', error: error.message });
    }
});

// 增加经验值
router.post('/level/add-exp', async (req, res) => {
    try {
        const userId = req.user.user_id;
        const { exp = 10 } = req.body; // 默认增加10经验
        
        // 更新经验值
        await db.query(
            'UPDATE user_levels SET exp = exp + ? WHERE user_id = ?',
            [exp, userId]
        );
        
        // 检查是否升级
        const leveledUp = await checkLevelUp(userId);
        
        res.json({
            code: 200,
            data: {
                exp_added: exp,
                leveled_up: leveledUp
            }
        });
    } catch (error) {
        console.error('增加经验失败:', error);
        res.status(500).json({ code: 500, message: '增加经验失败', error: error.message });
    }
});

// 检查并处理升级
async function checkLevelUp(userId) {
    try {
        const [userLevels] = await db.query(
            'SELECT * FROM user_levels WHERE user_id = ?',
            [userId]
        );
        
        if (userLevels.length === 0) return false;
        
        const userLevel = userLevels[0];
        
        // 获取下一等级要求
        const [nextConfig] = await db.query(
            'SELECT * FROM level_config WHERE level = ?',
            [userLevel.level + 1]
        );
        
        if (nextConfig.length === 0) return false; // 已是最高等级
        
        const next = nextConfig[0];
        
        // 检查经验是否足够升级
        if (userLevel.exp >= next.required_exp) {
            // 升级
            await db.query(
                'UPDATE user_levels SET level = level + 1 WHERE user_id = ?',
                [userId]
            );
            
            return {
                new_level: userLevel.level + 1,
                level_name: next.level_name,
                level_icon: next.level_icon
            };
        }
        
        return false;
    } catch (error) {
        console.error('检查升级失败:', error);
        return false;
    }
}

// 更新记账统计（供其他模块调用）
router.post('/update-stats', async (req, res) => {
    try {
        const userId = req.user.user_id;
        
        // 更新总记账次数
        await db.query(`
            UPDATE user_levels 
            SET total_records = (
                SELECT COUNT(*) FROM records WHERE user_id = ? AND is_deleted = 0
            )
            WHERE user_id = ?
        `, [userId, userId]);
        
        // 更新连续记账天数
        await updateStreakDays(userId);
        
        // 增加经验值（每次记账+10经验）
        await db.query(
            'UPDATE user_levels SET exp = exp + 10 WHERE user_id = ?',
            [userId]
        );
        
        // 检查升级
        const leveledUp = await checkLevelUp(userId);
        
        res.json({ code: 200, data: { updated: true, leveled_up: leveledUp } });
    } catch (error) {
        console.error('更新统计失败:', error);
        res.status(500).json({ code: 500, message: '更新失败', error: error.message });
    }
});

// 更新连续记账天数
async function updateStreakDays(userId) {
    try {
        const [userLevels] = await db.query(
            'SELECT * FROM user_levels WHERE user_id = ?',
            [userId]
        );
        
        if (userLevels.length === 0) return;
        
        const userLevel = userLevels[0];
        const today = new Date().toISOString().split('T')[0];
        const lastDate = userLevel.last_record_date;
        
        if (!lastDate) {
            // 第一次记账
            await db.query(
                'UPDATE user_levels SET streak_days = 1, last_record_date = ? WHERE user_id = ?',
                [today, userId]
            );
            return;
        }
        
        const lastDateStr = new Date(lastDate).toISOString().split('T')[0];
        
        if (lastDateStr === today) {
            // 今天已记过账，不更新
            return;
        }
        
        // 计算日期差
        const lastTimestamp = new Date(lastDateStr).getTime();
        const todayTimestamp = new Date(today).getTime();
        const dayDiff = Math.floor((todayTimestamp - lastTimestamp) / (1000 * 60 * 60 * 24));
        
        if (dayDiff === 1) {
            // 连续记账
            await db.query(
                'UPDATE user_levels SET streak_days = streak_days + 1, last_record_date = ? WHERE user_id = ?',
                [today, userId]
            );
        } else {
            // 中断了，重新开始
            await db.query(
                'UPDATE user_levels SET streak_days = 1, last_record_date = ? WHERE user_id = ?',
                [today, userId]
            );
        }
    } catch (error) {
        console.error('更新连续记账失败:', error);
    }
}

// 获取等级排行榜
router.get('/leaderboard', async (req, res) => {
    try {
        const [leaderboard] = await db.query(`
            SELECT 
                u.username,
                u.nickname,
                ul.level,
                ul.exp,
                ul.total_points,
                ul.total_records,
                ul.streak_days,
                lc.level_name,
                lc.level_icon
            FROM user_levels ul
            JOIN users u ON ul.user_id = u.user_id
            LEFT JOIN level_config lc ON ul.level = lc.level
            ORDER BY ul.level DESC, ul.exp DESC
            LIMIT 20
        `);
        
        res.json({ code: 200, data: leaderboard });
    } catch (error) {
        console.error('获取排行榜失败:', error);
        res.status(500).json({ code: 500, message: '获取失败', error: error.message });
    }
});

module.exports = router; 